package cn.caplike.demo.rabbitmq.springboot.idempotence_reliability.port.adapter.persistence.mybatis;

import cn.caplike.demo.rabbitmq.springboot.idempotence_reliability.domain.model.MessageDeliveryLog;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Description: 消息投递记录仓库
 *
 * @author LiKe
 * @version 1.0.0
 * @date 2020-09-01 17:19
 */
@Mapper
@Repository
public interface MessageDeliveryLogRepository {

    String TABLE_NAME = "MESSAGE_DELIVERY_LOG";

    /**
     * Description: 获取消息投递记录
     *
     * @param messageId 消息 ID
     * @return cn.caplike.demo.rabbitmq.springboot.idempotence.domain.model.MessageDeliveryLog
     * @author LiKe
     * @date 2020-09-02 15:47:38
     */
    @Select("SELECT * FROM " + TABLE_NAME + " WHERE MESSAGE_ID = #{messageId}")
    MessageDeliveryLog get(String messageId);

    /**
     * Description: 获取投递失败的消息记录
     *
     * @return java.util.List<cn.caplike.demo.rabbitmq.springboot.idempotence.domain.model.MessageDeliveryLog>
     * @author LiKe
     * @date 2020-09-03 10:21:08
     */
    @Select("SELECT * FROM " + TABLE_NAME + " WHERE STATUS = " + MessageDeliveryLog.Status.DELIVER_FAIL)
    List<MessageDeliveryLog> selectDeliveryFailed();

    /**
     * Description: 更新消息投递记录的状态
     *
     * @param messageId 消息 ID
     * @param status    消息状态
     * @return 更新条数
     * @author LiKe
     * @date 2020-09-02 20:45:50
     */
    @Update("UPDATE " + TABLE_NAME + " SET STATUS = #{status} WHERE MESSAGE_ID = #{messageId}")
    int updateStatus(String messageId, int status);

    /**
     * Description: 插入消息投递记录
     *
     * @param messageDeliveryLog {@link MessageDeliveryLog}
     * @return int 插入条数
     * @author LiKe
     * @date 2020-09-02 21:05:04
     */
    @InsertProvider(type = MessageDeliveryLogRepositoryProvider.class, method = "insert")
    int insert(@Param(MessageDeliveryLogRepositoryProvider.KEY_ENTITY) MessageDeliveryLog messageDeliveryLog);

    /**
     * Description: 更新指定字段的值
     *
     * @param messageDeliveryLog {@link MessageDeliveryLog}
     * @param updateFields       更新的字段数
     * @return int 更新条数
     * @author LiKe
     * @date 2020-09-03 10:55:22
     */
    @UpdateProvider(type = MessageDeliveryLogRepositoryProvider.class, method = "update")
    int update(
            @Param(MessageDeliveryLogRepositoryProvider.KEY_ENTITY) MessageDeliveryLog messageDeliveryLog,
            @Param(MessageDeliveryLogRepositoryProvider.KEY_UPDATE_FIELDS) String... updateFields
    );
}
